//
//  226. 反翻转二叉树.swift
//  Top600
//
//  Created by rjb on 2021/7/29.
//

import Foundation
class Solution226 {
    // 翻转二叉树
    // 采用递归的交换每个节点的左右子树
    @discardableResult
    func invertTree(_ root: TreeNode?) -> TreeNode? {
        guard let node = root else {
            return nil
        }
        let tmp = node.left
        node.left = node.right
        node.right = tmp
        invertTree(node.left)
        invertTree(node.right)
        return node
    }
    
    static func test() {
        let solution = Solution226()
        
        let node4 = TreeNode(4)
        let node2 = TreeNode(2)
        let node7 = TreeNode(7)
        let node1 = TreeNode(1)
        let node3 = TreeNode(3)
        let node6 = TreeNode(6)
        let node9 = TreeNode(9)
        
        node4.left = node2
        node2.left = node1
        node2.right = node3
        node4.right = node7
        node7.left = node6
        node7.right = node9
        
        let result = solution.invertTree(node4)
        print(result)
    }
}
